<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useServerStore } from '@/stores/server'
import ServerCard from '@/components/server/ServerCard.vue'
import ServerFilter from '@/components/server/ServerFilter.vue'
import type { Server } from '@/types/server'

const serverStore = useServerStore()
serverStore.pageSize = 9 // 设置每页加载9条记录
const loading = ref(false)
const initialLoading = ref(true) // 初始加载状态
const error = ref<string | null>(null)
const allServers = ref<Server[]>([])
const noMoreData = ref(false)
const animatedIndex = ref(-1) // 控制卡片动画

// 加载内部 Server 列表
const loadInternalServers = async (isInitialLoad = false) => {
  if ((loading.value && !isInitialLoad) || noMoreData.value) return
  
  if (isInitialLoad) {
    initialLoading.value = true
    // 初始加载时始终重置列表状态
    serverStore.setPage(1)
    allServers.value = []
    noMoreData.value = false
  } else {
    loading.value = true
  }
  error.value = null
  
  try {
    if (isInitialLoad) {
      // 已经在上面重置了状态
    }
    
    const result = await serverStore.fetchInternalServers()
    console.log('API返回内部 Server 数据:', result)
    
    // 将新数据追加到当前列表
    if (result && result.length > 0) {
      const startIndex = allServers.value.length
      allServers.value = [...allServers.value, ...result]
      
      // 触发卡片入场动画
      animateCards(startIndex)
    }
    
    // 检查是否还有更多数据
    if (allServers.value.length >= serverStore.internalTotalCount) {
      noMoreData.value = true
    }
  } catch (err: any) {
    console.error('加载失败:', err)
    error.value = err.message || '获取内部 Server 列表失败'
  } finally {
    if (isInitialLoad) {
      initialLoading.value = false
    }
    loading.value = false
  }
}

// 卡片动画
const animateCards = (startIndex: number) => {
  let delay = 0
  for (let i = startIndex; i < allServers.value.length; i++) {
    setTimeout(() => {
      animatedIndex.value = i
    }, delay)
    delay += 100
  }
}

// 处理滚动到底部加载更多
const handleScroll = () => {
  const scrollPosition = window.scrollY + window.innerHeight
  const documentHeight = document.documentElement.scrollHeight
  
  // 当滚动到距离底部200px时，加载更多数据
  if (scrollPosition >= documentHeight - 200 && !loading.value && !noMoreData.value && !initialLoading.value) {
    console.log('触发滚动加载, 当前页码:', serverStore.currentPage)
    // 增加页码
    serverStore.setPage(serverStore.currentPage + 1)
    loadInternalServers()
  }
}

// 处理筛选
const handleFilter = () => {
  loadInternalServers(true) // 重置并重新加载
}

// 监听store中servers的变化（用于调试）
watch(() => serverStore.internalServers, (newVal) => {
  console.log('store中内部 Server 数据变化:', newVal)
})

// 初始加载
onMounted(() => {
  console.log('内部 Server 组件挂载，开始加载数据')
  loadInternalServers(true)
  window.addEventListener('scroll', handleScroll)
})

// 清理事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

// 获取卡片动画类
const getCardAnimationClass = (index: number) => {
  return index <= animatedIndex.value ? 'animate-fade-in-up visible' : 'invisible opacity-0'
}
</script>

<template>
  <div>    
    <!--  Server 筛选组件 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 mb-8 transition-all duration-300 hover:shadow-lg">
      <ServerFilter :is-internal-only="true" @filter="handleFilter" />
    </div>
    
    <!-- 初始加载状态 -->
    <div v-if="initialLoading" class="flex flex-col items-center justify-center min-h-[300px]">
      <div class="relative">
        <div class="w-16 h-16 border-4 border-secondary-200 border-t-secondary-500 rounded-full animate-spin"></div>
        <div class="absolute top-0 left-0 w-16 h-16 border-4 border-transparent border-r-primary-500 rounded-full animate-spin-slow"></div>
      </div>
      <p class="mt-4 text-gray-600 dark:text-gray-300 text-lg">正在加载内部 Server 列表...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-else-if="error" class="bg-red-50 dark:bg-red-900/30 border-l-4 border-red-500 p-6 rounded-md my-6 shadow-lg animate-fade-in">
      <div class="flex items-start">
        <div class="flex-shrink-0">
          <svg class="h-6 w-6 text-red-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
        </div>
        <div class="ml-3">
          <h3 class="text-lg font-medium text-red-800 dark:text-red-300">加载失败</h3>
          <p class="mt-2 text-red-700 dark:text-red-200">{{ error }}</p>
          <button @click="loadInternalServers(true)" class="mt-4 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md shadow transition-colors duration-300">
            重试
          </button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="allServers.length === 0 && !initialLoading" class="text-center my-12 py-16 bg-gray-50 dark:bg-gray-800/50 rounded-lg shadow-inner animate-fade-in">
      <div class="max-w-md mx-auto">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-20 w-20 mx-auto mb-6 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <p class="text-2xl font-bold text-gray-700 dark:text-gray-200 mb-2">未找到匹配的内部MCP Server </p>
        <p class="text-gray-600 dark:text-gray-400 mb-6">尝试调整搜索条件或重置过滤器</p>
        <button @click="serverStore.resetFilters(); handleFilter()" class="px-6 py-3 bg-gradient-to-r from-secondary-500 to-primary-500 text-white rounded-lg shadow-md hover:shadow-lg transform hover:scale-105 transition-all duration-300">
          重置过滤器
        </button>
      </div>
    </div>
    
    <!--  Server 列表 -->
    <div v-else>
      <!-- 列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="(server, index) in allServers" 
          :key="server.id" 
          class="h-full transition-all duration-500 transform"
          :class="getCardAnimationClass(index)"
        >
          <ServerCard :server="server" />
        </div>
      </div>
      
      <!-- 加载更多提示 -->
      <div class="text-center my-8">
        <div v-if="loading" class="py-4">
          <div class="inline-flex items-center px-4 py-2 bg-secondary-100 dark:bg-secondary-900 rounded-full">
            <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-secondary-500 mr-3"></div>
            <span class="text-secondary-700 dark:text-secondary-300">加载更多...</span>
          </div>
        </div>
        <p 
          v-else-if="noMoreData" 
          class="text-gray-500 dark:text-gray-400 py-4 border-t border-gray-200 dark:border-gray-700 mt-6"
        >
          — 已显示全部 {{ allServers.length }} 条数据 —
        </p>
        <button 
          v-else 
          @click="loadInternalServers()" 
          class="mt-6 px-6 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 rounded-full text-gray-700 dark:text-gray-300 transition-colors duration-300"
        >
          点击加载更多
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.bg-pattern {
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.2'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}

.animate-spin-slow {
  animation: spin 3s linear infinite;
}

.animate-fade-in-up {
  animation: fadeInUp 0.6s ease-out forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 